package org.changs.nav.ui.set;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amap.api.maps.model.LatLng;
import com.jakewharton.rxbinding2.widget.RxTextView;

import org.changs.aplug.widget.irecyclerview.SimpleAdapter;
import org.changs.nav.R;
import org.changs.nav.databinding.CollectAddBinding;
import org.changs.nav.databinding.CollectAddItemBinding;
import org.changs.nav.delegate.MapSwitchDelegate;
import org.changs.nav.delegate.amap.AmapSearchHelper;
import org.changs.nav.delegate.amap.domain.SimpleLocation;
import org.changs.nav.delegate.global.AmapLocationTask;
import org.changs.nav.ui.nav.BaseMapFragment;

import javax.inject.Inject;

import aplug.data.db.CollectInfoHelper;
import aplug.data.db.SearchRecordHelper;
import aplug.data.db.mode.CollectInfo;
import aplug.data.db.mode.SearchRecord;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by 惠安 on 2017/11/24.
 */

public class CollectAddFragment extends BaseMapFragment {


    private static final String TAG_COLLECT_ID = "TAG_COLLECT_ID";

    /**
     * 添加收藏
     *
     * @param collectId 1 家、2 公司
     */
    public static CollectAddFragment newInstance(int collectId) {
        Bundle args = new Bundle();
        args.putInt(TAG_COLLECT_ID, collectId);
        CollectAddFragment fragment = new CollectAddFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private CollectAddBinding mBinding;
    private CollectAddAdapter mCollectAddAdapter;
    private int mCollectId;
    private String mCollectName;
    @Inject SearchRecordHelper mSearchRecordHelper;
    @Inject AmapSearchHelper mAmapSearchHelper;
    @Inject CollectInfoHelper mCollectInfoHelper;
    @Inject AmapLocationTask mAmapLocationTask;
    @Inject MapSwitchDelegate mMapSwitchDelegate;

    @Override
    public View setup(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.collect_add, container, false);
        return mBinding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        assert getArguments() != null;
        mCollectId = getArguments().getInt(TAG_COLLECT_ID);
        if (mCollectId == CollectInfoHelper.HOME_ID) {
            mCollectName = "家";
        } else if (mCollectId == CollectInfoHelper.COMPANY_ID) {
            mCollectName = "公司";
        } else {
            getContext().onBackPressed();
            return;
        }
        mBinding.etSearch.setHint(String.format("请输入%s的地址", mCollectName));
        RxTextView.textChanges(mBinding.etSearch).subscribe(text -> {
            boolean hasText = text.length() > 0;
            mBinding.btnSearch.setEnabled(hasText);
            mBinding.btnSearchClear.setVisibility(hasText ? View.VISIBLE : View.GONE);
        });
        mBinding.btnSearchClear.setOnClickListener(v -> mBinding.etSearch.setText(""));
        mBinding.btnSearch.setOnClickListener(v -> mAmapSearchHelper.search(this, mBinding.etSearch.getText().toString(), false, mCollectId));
        mBinding.btnMyLocation.setOnClickListener(v -> {
            SimpleLocation location = mAmapLocationTask.getLocation();
            if (location == null) {
                onError("定位失败,无法确定您的位置,请稍后再试");
                return;
            }
            mCollectInfoHelper.insertOrReplace(new CollectInfo((long) mCollectId, mCollectName, location.getAddress(),
                    location.getLatitude(), location.getLongitude()))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<Long>() {
                        @Override
                        public void accept(Long id) throws Exception {
                            mMapSwitchDelegate.addCollectMarket(id, new LatLng(location.getLatitude(), location.getLongitude()));
                            getFragmentManager().popBackStack();
                        }
                    });
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        //如果已经设置过该收藏点地址刚直接退出该界面
        mCollectInfoHelper.findOne((long) mCollectId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(collectInfo -> {
                    if (collectInfo.isValid()) {
                        getContext().onBackPressed();
                    } else {
                        setupSearchRecordList();
                    }
                });
    }

    private void setupSearchRecordList() {
        if (mCollectAddAdapter == null) {
            mCollectAddAdapter = new CollectAddAdapter();
            mCollectAddAdapter.setOnItemClickListener((view, position) -> {

            });
            mCollectAddAdapter.setOnItemClickListener(R.id.btn_add, (view, position) -> {
                SearchRecord searchRecord = mCollectAddAdapter.getData().get(position);
                if (searchRecord.getType() == SearchRecord.TYPE_NORMAL) {
                    mAmapSearchHelper.search(this, searchRecord.getName(), false);
                } else {
                    mCollectInfoHelper.insertOrReplace(new CollectInfo((long) mCollectId, mCollectName, searchRecord.getAddress(),
                            searchRecord.getLatitude(), searchRecord.getLongitude()))
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(id -> getFragmentManager().popBackStack());
                }
            });
            mBinding.rccView.setLayoutManager(new LinearLayoutManager(getContext()));
            mBinding.rccView.setIAdapter(mCollectAddAdapter);
            View footView = LayoutInflater.from(getContext()).inflate(R.layout.search_recode_foot,
                    mBinding.rccView, false);
            mBinding.rccView.addFooterView(footView);
            footView.setOnClickListener(v ->
                    mSearchRecordHelper.clear()
                            .subscribeOn(Schedulers.io())
                            .subscribe());
        } else {
            mCollectAddAdapter.getData().clear();
            mCollectAddAdapter.notifyDataSetChanged();
        }
        mSearchRecordHelper.findAll()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(searchRecords -> {
                    mCollectAddAdapter.getData().addAll(searchRecords);
                    mCollectAddAdapter.notifyDataSetChanged();
                });
    }

    private static class CollectAddAdapter extends SimpleAdapter<SearchRecord, CollectAddItemBinding> {
        public CollectAddAdapter() {
            super(R.layout.collect_add_item);
        }

        @Override
        protected void onBindViewHolder(CollectAddItemBinding binding, SearchRecord searchRecord, int position) {
            super.onBindViewHolder(binding, searchRecord, position);
            int type = searchRecord.getType();
            binding.tvName.setText(searchRecord.getName());
            if (type == SearchRecord.TYPE_NORMAL) {
                binding.tvAddress.setVisibility(View.GONE);
                binding.btnAdd.setVisibility(View.GONE);
            } else {
                binding.tvAddress.setVisibility(View.VISIBLE);
                binding.btnAdd.setVisibility(View.VISIBLE);
                binding.tvAddress.setText(searchRecord.getAddress());
            }
        }
    }
}

